<template>
  <div class="stock-management">
    <div class="page-title">库存台账管理</div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="物料编码">
          <el-input v-model="searchForm.materCode" placeholder="请输入物料编码" clearable />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="searchForm.materName" placeholder="请输入物料名称" clearable />
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="searchForm.batchCode" placeholder="请输入批次号" clearable />
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-input v-model="searchForm.warehouseName" placeholder="请输入仓库名称" clearable />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" style="width: 120px" clearable>
            <el-option label="出库" value="出库" />
            <el-option label="入库" value="入库" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 120px"  clearable>
            <el-option label="启用" value="10" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label=" 创建时间">
          <el-date-picker
            v-model="searchForm.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd" v-if="false">
        <el-icon><Plus /></el-icon> 新增库存
      </el-button>
      <el-button type="success" @click="handleExport">
        <el-icon><Download /></el-icon> 导出数据
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table :data="stockList" stripe v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" v-if="false"/>
        <el-table-column prop="materCode" label="物料编码" width="120" />
        <el-table-column prop="materName" label="物料名称" width="150" />
        <el-table-column prop="materType" label="物料分类" width="100" />
        <el-table-column prop="batchCode" label="批次号" width="120" />
        <el-table-column prop="warehouseName" label="仓库名称" width="120" />
        <el-table-column prop="locationName" label="库位名称" width="120" />
        <el-table-column prop="quantity" label="数量" width="100" align="right">
          <template #default="scope">
            {{ formatNumber(scope.row.quantity) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.type === '入库' ? 'success' : 'danger'">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90">
          <template #default="scope">
            <el-tag :type="scope.row.status === '已入库' ? 'success' :(scope.row.status ==='出库中'? 'info':'warning') ">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="spec" label="规格" width="120" />
        <el-table-column prop="siloName" label="筒仓名称" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="160" >
        <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" v-if="false">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 库存表单弹窗 -->
    <StockForm
      :visible="stockFormVisible"
      @update:visible="stockFormVisible = $event"
      :form-data="stockFormData"
      @submit="handleFormSubmit"
      @close="handleFormClose" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Download } from '@element-plus/icons-vue'
import { request } from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 导入组件
import StockForm from './StockForm.vue'

// 响应式数据
const loading = ref(false)
const stockList = ref([])
const stockFormVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  materCode: '',
  materName: '',
  batchCode: '',
  warehouseName: '',
  type: '',
  status: '',
  createTime:''
})
// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}
// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 库存表单数据
const stockFormData = reactive({
  id: '',
  materCode: '',
  materName: '',
  materType: '',
  batchCode: '',
  warehouseId: '',
  warehouseName: '',
  locationId: '',
  locationName: '',
  quantity: null,
  type: '入库',
  status: '10',
  spec: '',
  siloCode: '',
  siloName: '',
  isDeleted: false
})

// 物料类型映射
const materTypeMap = {
  '1': '原材料',
  '2': '半成品',
  '3': '成品',
  '4': '辅料'
}

// 获取物料类型名称
const getMaterTypeName = (typeId) => {
  return materTypeMap[typeId] || typeId
}

// 格式化数字显示
const formatNumber = (value) => {
  if (value === null || value === undefined) return '0'
  return Number(value).toLocaleString()
}

// 加载库存数据
const loadStockData = async () => {
  loading.value = true
  try {
    const params = {
      filter: {
        pageIndex: pagination.current,
        pageSize: pagination.size,
        orderBy: "createTime",
        isAscending: false
      },
      stock: {
        materCode: searchForm.materCode,
        materName: searchForm.materName,
        batchCode: searchForm.batchCode,
        warehouseName: searchForm.warehouseName,
        type: searchForm.type,
        status: searchForm.status,
        StockTimeScope:searchForm.createTime && searchForm.createTime.length > 0 ? searchForm.createTime[0] +'至'+ searchForm.createTime[1]: null
      }
    }
    
    // 调用后端API
    const response = await request.post('/Stock/stock_page', params)
    stockList.value = response.data
    pagination.total = response.totalCount
  } catch (error) {
    ElMessage.error('加载库存数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadStockData()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.current = 1
  loadStockData()
}

// 新增库存
const handleAdd = () => {
  // 重置表单数据
  Object.keys(stockFormData).forEach(key => {
    stockFormData[key] = ''
  })
  stockFormData.status = '10'
  stockFormData.type = '入库'
  stockFormData.quantity = 0
  stockFormData.isDeleted = false
  
  stockFormVisible.value = true
}

// 编辑库存
const handleEdit = (row) => {
  // 填充表单数据
  Object.keys(stockFormData).forEach(key => {
    if (row[key] !== undefined && row[key] !== null) {
      stockFormData[key] = row[key]
    }
  })
  
  stockFormVisible.value = true
}

// 删除库存
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除库存记录 "${row.materName}-${row.batchCode}" 吗？`, '提示', {
      type: 'warning'
    })
    
    // 调用删除API
    await request.delete(`/Stock/Delete/${row.id}`)
    ElMessage.success('删除成功')
    loadStockData()
    
  } catch (error) {
    console.log('删除取消或失败')
  }
}

// 表单提交处理
const handleFormSubmit = async (formData) => {
  try {
    if (formData.id) {
      // 编辑库存
      await request.post('/Stock/Save', formData)
      ElMessage.success('更新成功')
    } else {
      // 新增库存
      await request.post('/Stock/save-stock', formData)
      ElMessage.success('创建成功')
    }
    
    stockFormVisible.value = false
    loadStockData()
  } catch (error) {
    //debugger;
    ElMessage.error(error.response.data.error)
  }
}

// 表单关闭处理
const handleFormClose = () => {
  // 可以在这里添加关闭后的清理逻辑
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
  // 实际项目中这里实现导出功能
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadStockData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = page
  loadStockData()
}

// 页面加载时获取数据
onMounted(() => {
  loadStockData()
})
</script>

<style scoped>
.stock-management {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.action-buttons {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style>